const canvas = document.querySelector('canvas')
const c = canvas.getContext('2d')

canvas.width = 1440
canvas.height = 896

let mapPx = 45
let mapPy = 28

const collisionsMap = [] // 地图坐标
for (let i = 0; i < collisions.length; i += mapPx) {
  collisionsMap.push(collisions.slice(i, mapPx + i))
}

const battleZonesMap = []
for (let i = 0; i < battleZonesData.length; i += 70) {
  battleZonesMap.push(battleZonesData.slice(i, 70 + i))
}

const charactersMap = []
for (let i = 0; i < charactersMapData.length; i += 70) {
  charactersMap.push(charactersMapData.slice(i, 70 + i))
}
console.log(charactersMap)

const boundaries = []
const offset = {
  x: 0,
  y: 0
}

let timer = null

collisionsMap.forEach((row, i) => {
  row.forEach((symbol, j) => {
    if (symbol === 1)
      boundaries.push(
        new Boundary({
          position: {
            x: j * Boundary.width + offset.x,
            y: i * Boundary.height + offset.y
          }
        })
      )
  })
})

// let mapNodeData = createMapGrid(collisionsMap) // 创建地图节点数据

const battleZones = []

battleZonesMap.forEach((row, i) => {
  row.forEach((symbol, j) => {
    if (symbol === 1025)
      battleZones.push(
        new Boundary({
          position: {
            x: j * Boundary.width + offset.x,
            y: i * Boundary.height + offset.y
          }
        })
      )
  })
})

const characters = []
const villagerImg = new Image()
villagerImg.src = './img/villager/Idle.png'

const oldManImg = new Image()
oldManImg.src = './img/oldMan/Idle.png'

charactersMap.forEach((row, i) => {
  row.forEach((symbol, j) => {
    // 1026 === villager
    if (symbol === 1026) {
      characters.push(
        new Character({
          position: {
            x: j * Boundary.width + offset.x,
            y: i * Boundary.height + offset.y
          },
          image: villagerImg,
          frames: {
            max: 4,
            hold: 60
          },
          scale: 3,
          animate: true,
          dialogue: ['...', 'Hey mister, have you seen my Doggochu?']
        })
      )
    }
    // 1031 === oldMan
    else if (symbol === 1031) {
      characters.push(
        new Character({
          position: {
            x: j * Boundary.width + offset.x,
            y: i * Boundary.height + offset.y
          },
          image: oldManImg,
          frames: {
            max: 4,
            hold: 60
          },
          scale: 3,
          dialogue: ['My bones hurt.']
        })
      )
    }

    if (symbol !== 0) {
      boundaries.push(
        new Boundary({
          position: {
            x: j * Boundary.width + offset.x,
            y: i * Boundary.height + offset.y
          }
        })
      )
    }
  })
})

const image = new Image()
image.src = './img/map/map_1.png'

const foregroundImage = new Image()
foregroundImage.src = './img/foregroundObjects.png'

const playerDownImage = new Image()
playerDownImage.src = './img/player/playerDown.png'

const playerUpImage = new Image()
playerUpImage.src = './img/player/playerUp.png'

const playerLeftImage = new Image()
playerLeftImage.src = './img/player/playerLeft.png'

const playerRightImage = new Image()
playerRightImage.src = './img/player/playerRight.png'

const swordRightImage = new Image()
swordRightImage.src = './img/arms/swordRight.png'
const swordLeftImage = new Image()
swordLeftImage.src = './img/arms/swordLeft.png'

const playerPos = {
  x: canvas.width / 2 - 48 / 3 / 2,
  y: canvas.height / 2 - 20 / 2 + 200
}
// const playerPos = {
//   x: 3600 / 2 + offset.x,
//   y: 1920 / 2 + offset.y
// }

console.log(playerPos);

// const player = new Sprite({
//   position: {
//     x: playerPos.x,
//     y: playerPos.y
//   },
//   image: playerDownImage,
//   frames: {
//     max: 3,
//     hold: 10
//   },
//   sprites: {
//     up: playerUpImage,
//     left: playerLeftImage,
//     right: playerRightImage,
//     down: playerDownImage
//   },
//   scale:2.5
// })
let player = null

const swordLeftPos = {
   x: -30,
   y: 5
}

const swordRightPos = {
  x: 30,
  y: 5
}

const sword = new Sprite({
  position: {
    x: playerPos.x + swordLeftPos.x,
    y: playerPos.y + swordLeftPos.y
  },
  image: swordLeftImage,
  sprites: {
    up: swordRightImage,
    left: swordLeftImage,
    right: swordRightImage,
    down: swordLeftImage
  },
  scale:2.6
})

const background = new Sprite({
  position: {
    x: offset.x,
    y: offset.y
  },
  image: image
})

const foreground = new Sprite({
  position: {
    x: offset.x,
    y: offset.y
  },
  image: foregroundImage
})

const keys = {
  w: {
    pressed: false
  },
  a: {
    pressed: false
  },
  s: {
    pressed: false
  },
  d: {
    pressed: false
  }
}

const movables = [
  background,
  ...boundaries,
  // foreground,
  ...battleZones,
  ...characters
]
const renderables = [
  background,
  ...boundaries,
  ...battleZones,
  ...characters,
  // ...playerList,
  // sword,
  // foreground
]

const battle = {
  initiated: false
}

let clickData = null
let isMove = false


function animate() {
  const animationId = window.requestAnimationFrame(animate)
  renderables.forEach((renderable) => {
    renderable.draw()
  })
  if (player) player.draw()
  // if (lastKey === 'w' || lastKey === 'a')
  // {
  //   // sword.draw()
  //   if (player) player.draw()
  //   // player.draw()
  // }
  // else
  // {
  //   // player.draw()
  //   if (player) player.draw()
    
  //   // sword.draw()
  // }
  if (playerList.length) {
    playerList.forEach((item) => {
      if (item.toward === 'down')
      {
        item.image = item.sprites.down
      }
      else if (item.toward === 'up')
      {
        item.image = item.sprites.up
      }
      else if (item.toward === 'right')
      {
        item.image = item.sprites.right
      }
      else if (item.toward === 'left')
      {
        item.image = item.sprites.left
      }
      item.draw();
    })
  }
  // foreground.draw()
  let moving = true

  if (player) 
  {
    player.animate = false
  }
  

  if (battle.initiated) return
  // if (!clickData) return
  // let coords = clickData
  // if (isMove)
  // {
  //   console.log(coords);
  //   for (let i = 0; i < coords.length; i++)
  //   {
  //     let rangeX = player.position.x - coords[i][0]
  //     let rangeY = player.position.y - coords[i][1]
  //     if (rangeX > 0)
  //     {
  //         // 往左移动
  //         // element.position.x -= rangeX
  //         let length = Math.round(Math.abs(rangeX) / 3)
  //         for(let i = 0; i < length; i++)
  //         {
  //           player.position.x -= 3
  //           player.draw()
  //         }
  //     }
  //     else
  //     {
  //         // 往右移动
  //         // element.position.x += rangeX
  //         let length = Math.round(Math.abs(rangeX) / 3)
  //         for(let i = 0; i < length; i++)
  //         {
  //           player.position.x += 3
  //           player.draw()
  //         }
  //     }
  
  //     if (rangeY > 0)
  //     {
  //         // 往上移动
  //         player.animate = true
  //         player.toward = 'up'
  //         player.image = player.sprites.up
  //         // element.position.y -= rangeY
  //         let length = Math.round(Math.abs(rangeY) / 3)
  //         for(let i = 0; i < length; i++)
  //         {
  //           console.log(player.position.y);
  //           player.position.y -= 3
  //           player.draw()
  //         }
  //     }
  //     else
  //     {
  //         // 往下移动
  //         // element.position.y += rangeY
  //         let length = Math.round(Math.abs(rangeY) / 3)
  //         for(let i = 0; i < length; i++)
  //         {
  //           player.position.y += 3
  //           player.draw()
  //         }
  //     }
  //     // if (player) player.draw()
  //     player.position.originX = coords[i][0]
  //     player.position.originY = coords[i][1]
  //   }
  //   isMove = false
  // }
 

  // activate a battle
  if (keys.w.pressed || keys.a.pressed || keys.s.pressed || keys.d.pressed) {
    player.isMove = true
    for (let i = 0; i < battleZones.length; i++) {
      const battleZone = battleZones[i]
      const overlappingArea =
        (Math.min(
          player.position.x + player.width,
          battleZone.position.x + battleZone.width
        ) -
          Math.max(player.position.x, battleZone.position.x)) *
        (Math.min(
          player.position.y + player.height,
          battleZone.position.y + battleZone.height
        ) -
          Math.max(player.position.y, battleZone.position.y))
      if (
        rectangularCollision({
          rectangle1: player, 
          rectangle2: battleZone
        }) &&
        overlappingArea > (player.width * player.height) / 2 &&
        Math.random() < 0.01
      ) {
        // deactivate current animation loop
        window.cancelAnimationFrame(animationId)

        audio.Map.stop()
        audio.initBattle.play()
        audio.battle.play()

        battle.initiated = true
        gsap.to('#overlappingDiv', {
          opacity: 1,
          repeat: 3,
          yoyo: true,
          duration: 0.4,
          onComplete() {
            gsap.to('#overlappingDiv', {
              opacity: 1,
              duration: 0.4,
              onComplete() {
                // activate a new animation loop
                initBattle()
                animateBattle()
                gsap.to('#overlappingDiv', {
                  opacity: 0,
                  duration: 0.4
                })
              }
            })
          }
        })
        break
      }
    }
  }

  if (keys.w.pressed && lastKey === 'w') {
 
    player.animate = true
    player.toward = 'up'
    player.image = player.sprites.up
    sword.image = sword.sprites.up
    sword.position.x = playerPos.x + swordRightPos.x
    // sword.draw()
    // player.draw()

    

    checkForCharacterCollision({
      characters,
      player,
      characterOffset: { x: 0, y: 3 }
    })

    for (let i = 0; i < boundaries.length; i++) {
      const boundary = boundaries[i]
      if (
        rectangularCollision({
          rectangle1: player,
          rectangle2: {
            ...boundary,
            position: {
              x: boundary.position.x,
              y: boundary.position.y + 3
            }
          }
        })
      ) {
        moving = false
        // player.isMove = false
        break
      }
    }

    // newPlayerY = background.position.y
    if (moving) {
      newPlayerY = newPlayerY - 3
      player.position.y -= 3
     
      if (playerList.length) {
        playerList.forEach((item) => {
          item.position.y += 3
          // item.draw();
        })
      }
      // movables.forEach((movable) => {
      //   movable.position.y += 3
      // })
    }
  } else if (keys.a.pressed && lastKey === 'a') {
    player.animate = true
    player.toward = 'left'
    player.image = player.sprites.left
    sword.image = sword.sprites.down
    sword.position.x = playerPos.x + swordLeftPos.x + 10
    // sword.draw()
    // player.draw()

    checkForCharacterCollision({
      characters,
      player,
      characterOffset: { x: 3, y: 0 }
    })

    for (let i = 0; i < boundaries.length; i++) {
      const boundary = boundaries[i]
      if (
        rectangularCollision({
          rectangle1: player,
          rectangle2: {
            ...boundary,
            position: {
              x: boundary.position.x + 3,
              y: boundary.position.y
            }
          }
        })
      ) {
        moving = false
        // player.isMove = false
        break
      }
    }

    if (moving) {
      newPlayerX = newPlayerX - 3
      player.position.x -= 3
      if (playerList.length) {
        playerList.forEach((item) => {
          item.position.x += 3
        })
      }
      // movables.forEach((movable) => {
      //   movable.position.x += 3
      // })
    }
     
  } else if (keys.s.pressed && lastKey === 's') {
    player.animate = true
    player.toward = 'down'
    player.image = player.sprites.down
    sword.image = sword.sprites.down
    sword.position.x = playerPos.x + swordLeftPos.x
    // player.draw()
    // sword.draw()

    checkForCharacterCollision({
      characters,
      player,
      characterOffset: { x: 0, y: -3 }
    })

    for (let i = 0; i < boundaries.length; i++) {
      const boundary = boundaries[i]
      if (
        rectangularCollision({
          rectangle1: player,
          rectangle2: {
            ...boundary,
            position: {
              x: boundary.position.x,
              y: boundary.position.y - 3
            }
          }
        })
      ) {
        moving = false
        // player.isMove = false
        break
      }
    }

    if (moving) {
      newPlayerY = newPlayerY + 3
      player.position.y += 3
      if (playerList.length) {
        playerList.forEach((item) => {
          item.position.y -= 3
        })
      }
      // movables.forEach((movable) => {
      //   movable.position.y -= 3
      // })
    }
      
  } else if (keys.d.pressed && lastKey === 'd') {
    player.animate = true
    player.toward = 'right'
    player.image = player.sprites.right
    sword.image = sword.sprites.up
    sword.position.x = playerPos.x + swordRightPos.x - 10
    // player.draw()
    // sword.draw()

    checkForCharacterCollision({
      characters,
      player,
      characterOffset: { x: -3, y: 0 }
    })

    for (let i = 0; i < boundaries.length; i++) {
      const boundary = boundaries[i]
      if (
        rectangularCollision({
          rectangle1: player,
          rectangle2: {
            ...boundary,
            position: {
              x: boundary.position.x - 3,
              y: boundary.position.y
            }
          }
        })
      ) {
        console.log('碰撞到了');
        moving = false
        // player.isMove = false
        break
      }
    }

    if (moving) {
      newPlayerX = newPlayerX + 3
      player.position.x += 3
      if (playerList.length) {
        playerList.forEach((item) => {
          item.position.x -= 3
        })
      }
      // movables.forEach((movable) => {
      //   movable.position.x -= 3
      // })
    }
      
  }
}
// animate()

let lastKey = ''

window.addEventListener('keydown', (e) => {
  if (player.isInteracting) {
    switch (e.key) {
      case ' ':
        player.interactionAsset.dialogueIndex++

        const { dialogueIndex, dialogue } = player.interactionAsset
        if (dialogueIndex <= dialogue.length - 1) {
          document.querySelector('#characterDialogueBox').innerHTML =
            player.interactionAsset.dialogue[dialogueIndex]
          return
        }

        // finish conversation
        player.isInteracting = false
        player.interactionAsset.dialogueIndex = 0
        document.querySelector('#characterDialogueBox').style.display = 'none'

        break
    }
    return
  }

  switch (e.key) {
    case ' ':
      if (!player.interactionAsset) return

      // beginning the conversation
      const firstMessage = player.interactionAsset.dialogue[0]
      document.querySelector('#characterDialogueBox').innerHTML = firstMessage
      document.querySelector('#characterDialogueBox').style.display = 'flex'
      player.isInteracting = true
      break
    case 'w':
      keys.w.pressed = true
      lastKey = 'w'
      break
    case 'a':
      keys.a.pressed = true
      lastKey = 'a'
      break

    case 's':
      keys.s.pressed = true
      lastKey = 's'
      break

    case 'd':
      keys.d.pressed = true
      lastKey = 'd'
      break
  }
})

function cancelMove () {
  // timer && clearTimeout(timer)
  // timer = setTimeout(() => {
  //   player.isMove = false
  // }, 500);
}

window.addEventListener('keyup', (e) => {
  switch (e.key) {
    case 'w':
      keys.w.pressed = false
      cancelMove()
      break
    case 'a':
      keys.a.pressed = false
      cancelMove()
      break
    case 's':
      keys.s.pressed = false
      cancelMove()
      break
    case 'd':
      keys.d.pressed = false
      cancelMove()
      break
  }
})

let clicked = false
window.addEventListener('click', (e) => {
  if (!clicked) {
    audio.Map.play()
    clicked = true
  }
  console.log('我是window的click');
})

function go (e) {
  let clickX = e.clientX - canvas.offsetLeft;
  let clickY = e.clientY - canvas.offsetTop;
  let targetPosition = {
    x: e.offsetX,
    y: e.offsetY
  }
  let originPosition = {
    x: player.position.originX,
    y: player.position.originY
  }
  console.log('我是canvas的click', e.offsetX, e.offsetY);
  // a*算法算出最佳路径
  let currentNodeY = parseInt((originPosition.x - offset.x) / player.width)
  let currentNodeX = parseInt((originPosition.y - offset.y) / player.height)
  let targetNodeY = parseInt((targetPosition.x - offset.x) / player.width)
  let targetNodeX = parseInt((targetPosition.y - offset.y) / player.height)
  console.log(mapNodeData);
  console.log('目前坐标的node节点',currentNodeX, currentNodeY);
  console.log('目标坐标的node节点',targetNodeX, targetNodeY);
  console.log(mapNodeData[currentNodeX][currentNodeY], mapNodeData[targetNodeX][targetNodeY]);
  let start = mapNodeData[currentNodeX][currentNodeY]
  let end = mapNodeData[targetNodeX][targetNodeY]
  let path = astar(start, end, mapNodeData)
  console.log(path);
  // 将节点转换为坐标
  let coords = []
  for (let k = 0; k < path.length; k++) {
    let y = path[k].x * player.height + offset.y
    let x = path[k].y * player.width + offset.x
    coords[k] = [x, y]
  }
  console.log(coords);
  return coords

}


// canvas.addEventListener('click', (e) => {
//   isMove = false
//   timer && clearTimeout(timer)
//   timer = setTimeout(() => {
//     // clickData = e
//     clickData = go(e)
//     isMove = true
//   }, 200);
// })

// canvas.addEventListener('mouseup', () => {
//   isClick = false
// })
